package cn.hinglo.common.util;

import cn.hutool.core.codec.Base64;
import cn.hutool.core.io.FileUtil;
import cn.hutool.crypto.SecureUtil;
import cn.hutool.json.JSON;
import cn.hutool.json.JSONUtil;
import com.jfinal.upload.UploadFile;
import com.qiniu.common.QiniuException;
import com.qiniu.common.Zone;
import com.qiniu.http.Response;
import com.qiniu.storage.Configuration;
import com.qiniu.storage.UploadManager;
import com.qiniu.util.Auth;
import lombok.extern.slf4j.Slf4j;

import java.io.File;

/**
 * @createTime: 2019/7/17 : 16:30
 * @author: HingLo
 * @description: 七牛文件上传工具
 */
@Slf4j
public class QiniuFileUploadKit {
    /***
     * AccessKey
     */
    private static final String ACCESS_KEY = PropertiesKit.get("qiNiuAccessKey");
    /***
     * SecretKey
     */
    private static final String SECRET_KEY = PropertiesKit.get("qiNiuSecretKey");
    /***
     * Bucket
     */
    private static final String BUCKET = PropertiesKit.get("qiNiuBucket");

    /***
     * URL前缀
     */
    private static final String URL = PropertiesKit.get("qiNiuUrl");

    /***
     * 文件上传
     * @param body 文件字节数组
     * @return 返回文件名称
     */
    private static String upload(byte[] body) {
        Configuration cfg = new Configuration(Zone.zone0());
        UploadManager uploadManager = new UploadManager(cfg);
        Auth auth = Auth.create(ACCESS_KEY, SECRET_KEY);
        String upToken = auth.uploadToken(BUCKET);
        try {
            // 默认使用文件的hash作为文件名称
            Response response = uploadManager.put(body, null, upToken);
            String result = response.bodyString();
            JSON json = JSONUtil.parse(result);
            return URL + JSONUtil.getByPath(json, "hash").toString();
        } catch (QiniuException e) {
            log.error("文件上传到七牛云发生错误,=>", e);
            return null;
        }
    }

    /***
     * Jfinal 默认文件上传对象
     * @param uploadFile 文件对象
     * @return 完整的url
     */
    public static String uploadFile(UploadFile uploadFile) {
        return upload(FileUtil.readBytes(uploadFile.getFile()));
    }

    /***
     *  文件对象
     * @param file 文件对象
     * @return 完整的url
     */
    public static String uploadFile(File file) {
        return upload(FileUtil.readBytes(file));
    }

    /***
     *  文件路径
     * @param path 文件路径
     * @return 完整的url
     */
    public static String uploadFile(String path) {
        return upload(FileUtil.readBytes(path));
    }


    /***
     *
     * 0x16+文件的内容的sha1值
     * 七牛云小于4M文件名称默认算法
     * @param body 文件内容
     * @return 返回结果
     */
    private static String fileName(byte[] body) {
        byte[] digest = SecureUtil.createMessageDigest("sha1").digest(body);
        byte[] hashData = new byte[digest.length + 1];
        System.arraycopy(digest, 0, hashData, 1, digest.length);
        hashData[0] = 0x16;
        return Base64.encodeUrlSafe(hashData);
    }
}
